<?php
/**
* For Mobile connectors
* Authenticate (or login) one profile from mobile
* @author trungdt
* @since Dec 9, 2012
* 
* Input
* - username
* - password
* 
* Output
* {
*   status: OK | NOT_AUTHENTICATED | NOT_VALID 
*   session_id : text
*   user_id : int
* }
* 
* Client need to keep this session id and send it back to server for every request.
* If session is not valid, then no result will be replied to client
* Session timeout = 15 mins
*/
    if (!defined('EXPONENT')) exit('');
    global $db;
    // include the mobile connectors
    include_once(BASE."modules/profilemodule/mobile_connector.php");
    
    $ret = null; // init object
    $ret->status = "NOT_VALID";
    $ret->session_id = "";
    
    if (isset($_POST['username']) && isset($_POST['password']))
    {
        $username = _ab_safe_html_string($_POST['username']);
        $password = _ab_safe_html_string($_POST['password']);
        // login with case 1
        
        $m_user = exponent_users_getUserByName($username);
        if (isset($m_user->id) && exponent_users_authenticate($m_user, $password))
        {
            // authenticate ok
            $ret->status = "OK";
            $ret->session_id = profile_mobile_get_current_clientGUIID();
            $ret->user_id = $m_user->id;
            
            // insert into table mobile session
            $data = null;
            $data->session_id = $ret->session_id;
            $data->username = $username;
            $data->last_response = time();
            $data->user_id = $m_user->id;
            $db->insertObject($data, "profilemodule_mobilesession");
        }
        else
        {
            $ret->status = "NOT_AUTHENTICATED";
            $ret->session_id = "";
        }
    }
    
    echo json_encode($ret);
    die();
    
?>